package bean.control;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import bean.entity.Announce;
import bean.entityField.AnnounceField;
import bean.persistence.PersistenceHelper;

public class AnnounceMgr {
	public static void addAnnounce(String title, String content) {
		PersistenceHelper pHelper = new PersistenceHelper();
		Announce ann = new Announce(null, title, content, new Date());
		
		pHelper.openPersistence();
		try {
			pHelper.insert(ann);
		} finally {
			pHelper.closePersistence();
		}
	}
	
	@SuppressWarnings("unchecked")
	public static List<Announce> queryAllAnnounceOrderByPoTime() {
		PersistenceHelper pHelper = new PersistenceHelper();
		
		pHelper.openPersistence();
		pHelper.openQuery(Announce.class);
		try {
			List<Announce> annList = (List<Announce>)pHelper.query(null, AnnounceField.POTIME + " desc", null, null, null);
			List<Announce> copyList = new LinkedList<Announce>();
			
			for (Announce ann: annList) {
				Announce copyAnn = new Announce(ann.getKey(), ann.getTitle(), ann.getContent(), ann.getPoTime());
				copyList.add(copyAnn);
			}
			
			return copyList;
		} finally {
			pHelper.closeQuery();
			pHelper.closePersistence();
		}
	}
	
	public static Announce getAnnounceById(long id) {
		PersistenceHelper pHelper = new PersistenceHelper();
		
		pHelper.openPersistence();
		try {
			Announce ann = (Announce)pHelper.getById(Announce.class, id);
			Announce copyAnn = new Announce(ann.getKey(), ann.getTitle(), ann.getContent(), ann.getPoTime());
			
			return copyAnn;
		} finally {
			pHelper.closePersistence();
		}
	}
	
	public static void modifyAnnounceById(long id, String title, String content) {
		PersistenceHelper pHelper = new PersistenceHelper();
		
		pHelper.openPersistence();
		try {
			Announce ann = (Announce)pHelper.getById(Announce.class, id);
			
			ann.setTitle(title);
			ann.setContent(content);
			ann.setPoTime(new Date());
		} finally {
			pHelper.closePersistence();
		}
	}
	
	public static void delAnnounceById(long id) {
		PersistenceHelper pHelper = new PersistenceHelper();
		
		pHelper.openPersistence();
		try {
			Announce ann = (Announce)pHelper.getById(Announce.class, id);
			pHelper.delete(ann);
		} finally {
			pHelper.closePersistence();
		}
	}
}
